package com.fs.luban.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * 请求工具类
 */
public class RequestUtils {

	/**
	 * 判断请求是否是ajax请求
	 */
	public static boolean isAjax(HttpServletRequest request) {
		String reqHeader = request.getHeader("X-Requested-With");
		return StringUtils.isNotBlank(reqHeader) && reqHeader.equalsIgnoreCase("XMLHttpRequest");
	}

	/**
	 * 获取最终的ip地址
	 */
	public static String getRequestIpAddr(HttpServletRequest request) {
		String loginIp = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(loginIp) || "unknown".equalsIgnoreCase(loginIp))
			loginIp = request.getHeader("Proxy-Client-lastLoginIp");
		if (StringUtils.isBlank(loginIp) || "unknown".equalsIgnoreCase(loginIp)) {
			loginIp = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(loginIp) || "unknown".equalsIgnoreCase(loginIp)) {
			loginIp = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(loginIp) || "unknown".equalsIgnoreCase(loginIp))
			loginIp = request.getHeader("WL-Proxy-Client-lastLoginIp");
		if (StringUtils.isBlank(loginIp) || "unknown".equalsIgnoreCase(loginIp))
			loginIp = request.getHeader("HTTP_CLIENT_lastLoginIp");
		if (StringUtils.isBlank(loginIp) || "unknown".equalsIgnoreCase(loginIp))
			loginIp = request.getHeader("HTTP_X_FORWARDED_FOR");
		if (StringUtils.isBlank(loginIp) || "unknown".equalsIgnoreCase(loginIp)) {
			loginIp = request.getRemoteAddr();
		}
		if ("127.0.0.1".equals(loginIp) || "0:0:0:0:0:0:0:1".equals(loginIp))
			try {
				loginIp = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException unknownhostexception) {
				unknownhostexception.printStackTrace();
			}
		return loginIp;
	}

}
